package xyz.ibenben.zhongdian.system.service.sys.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import xyz.ibenben.zhongdian.common.annotation.SystemServiceLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.system.dao.sys.SysUserRoleDao;
import xyz.ibenben.zhongdian.system.entity.sys.SysUserRole;
import xyz.ibenben.zhongdian.system.service.sys.SysUserRoleService;

/**
 * 系统用户角色服务实现类
 * 系统级用户所使用的，是权限系统中的一部分
 * 提供了一些基本的服务，如添加用户角色、根据用户主键删除记录等方法。
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Service
public class SysUserRoleServiceImpl implements SysUserRoleService {
	private final SysUserRoleDao sysUserRoleDao;

	@Autowired
	public SysUserRoleServiceImpl(SysUserRoleDao sysUserRoleDao) {
		this.sysUserRoleDao = sysUserRoleDao;
	}

	/**
	 * addUserRole用户角色记录
	 * @param userRole 实体
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
	@SystemServiceLog(description = "addUserRole用户角色记录")
	public void addUserRole(SysUserRole userRole) {
		//删除
		this.deleteByUserId(userRole.getUserId());
		//添加
		String[] roleids = userRole.getRoleIds().split(Constants.COMMA);
		for (String roleId : roleids) {
			//组装实体
			SysUserRole u = new SysUserRole();
			u.setUserId(userRole.getUserId());
			u.setRoleId(Long.parseLong(roleId));
			//保存实体
			sysUserRoleDao.insert(u);
		}
	}

	/**
	 * deleteByUserId用户角色记录
	 * @param userId 用户主键
	 * @return 是否删除成功
	 */
	@Transactional
	@Override
	@SystemServiceLog(description = "deleteByUserId用户角色记录")
	public int deleteByUserId(Object userId) {
		Example example = new Example(SysUserRole.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("userId", userId);
		//根据用户主键删除记录
		return sysUserRoleDao.deleteByExample(example);
	}

}
